package com.sfj.system.service.task;

import com.kaka.starter.token.util.HeaderUtils;
import com.sfj.common.exception.CheckException;
import com.sfj.system.dto.task.*;
import com.sfj.system.entity.ProblemProcessEntity;
import com.sfj.system.entity.TaskEntity;
import com.sfj.system.entity.TaskProblemEntity;
import com.sfj.system.entity.TaskReviewEntity;
import com.sfj.system.enums.ProblemStatusEnum;
import com.sfj.system.enums.TaskStatusEnum;
import com.sfj.system.mapper.TaskMapper;
import com.sfj.system.mapper.TaskReviewMapper;
import com.sfj.system.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @Date 2025/07/01
 */
@Service
public class TaskService {
    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TaskReviewMapper taskReviewMapper;
    @Autowired
    private ProblemService problemService;

    @Autowired
    private ProblemProcessService problemProcessService;

    @Transactional
    public void createTask(TaskAddDTO taskAddDTO) {
        TaskEntity taskEntity = buildAddEntity(taskAddDTO);

        taskEntity.setCreateTime(LocalDateTime.now().withNano(0));
        taskMapper.insert(taskEntity);

        // 保存问题列表
        List<TaskProblemEntity> problemList = new ArrayList<>(taskAddDTO.getProblemList().size());
        for (TaskProblemDTO problemDTO : taskAddDTO.getProblemList()) {
            TaskProblemEntity problemEntity = new TaskProblemEntity();
            BeanUtils.copyProperties(problemDTO, problemEntity);
            problemEntity.setTaskId(taskEntity.getTaskId());
            problemEntity.setIndex(problemDTO.getIndex());
            //初始状态未整改
            problemEntity.setStatus(ProblemStatusEnum.NOT_RECTIFIED.getCode());
            problemList.add(problemEntity);
        }
        problemService.batchSave(problemList);
    }

    //构建督察任务
    private TaskEntity buildAddEntity(TaskAddDTO taskDTO) {
        TaskEntity taskEntity = new TaskEntity();
        // 设置基本字段
        taskEntity.setSource(taskDTO.getSource());
        taskEntity.setProblemType(taskDTO.getProblemType());
        taskEntity.setRequirements(taskDTO.getRequirements());
        taskEntity.setLeaderInstruction(taskDTO.getLeaderInstruction() != null && taskDTO.getLeaderInstruction() ? 1 : 0);
        taskEntity.setLeaderRemark(taskDTO.getLeaderRemark());
        taskEntity.setLeaderFile(taskDTO.getLeaderFile());
        taskEntity.setRfUsers(taskDTO.getRfUsers());
        taskEntity.setRfUnits(taskDTO.getRfUnits());
        taskEntity.setRfStartDate(taskDTO.getRfStartDate());
        taskEntity.setRfEndDate(taskDTO.getRfEndDate());
        taskEntity.setAuditor(taskDTO.getAuditor());
        taskEntity.setRemark(taskDTO.getRemark());
        taskEntity.setReportDeptId(taskDTO.getReportDeptId());
        taskEntity.setReportUserId(taskDTO.getReportUserId());
        taskEntity.setTaskFile(taskDTO.getTaskFile());

        // 设置初始状态为"待审核"
        taskEntity.setStatus(TaskStatusEnum.REVIEW.getCode());

        // 设置时间戳
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        taskEntity.setCreateTime(localDateTime);
        taskEntity.setUpdateTime(localDateTime);

        return taskEntity;
    }

    @Transactional
    public void updateTask(TaskAddDTO taskDTO) {
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskDTO, taskEntity);
        taskEntity.setUpdateTime(LocalDateTime.now().withNano(0));
        taskEntity.setStatus(TaskStatusEnum.REVIEW.getCode());
        taskMapper.update(taskEntity);

        // 先删除旧问题，再添加新问题
        problemService.del(taskDTO.getTaskId());
        if (taskDTO.getProblemList() != null && !taskDTO.getProblemList().isEmpty()) {
            for (TaskProblemDTO problemDTO : taskDTO.getProblemList()) {
                TaskProblemEntity problemEntity = new TaskProblemEntity();
                BeanUtils.copyProperties(problemDTO, problemEntity);
                problemEntity.setTaskId(taskDTO.getTaskId());
                problemService.insert(problemEntity);
            }
        }

    }

    @Transactional
    public void deleteTask(Integer taskId) {
        // 先删除问题

        problemService.del(taskId);
        // 再删除任务
        taskMapper.delete(taskId);
    }


    public void withdrawTask(Integer taskId) {
        //todo 所有状态都可以撤回吗 已完成的任务不可撤回？
        taskMapper.updStatus(taskId, TaskStatusEnum.WITHDRAW.getCode());
    }

    public void taskFinish(Integer taskId) {
        taskMapper.updStatus(taskId, TaskStatusEnum.REVIEWED.getCode());
    }

    //只有待审核状态的任务才可以审批
    @Transactional
    public void reviewTask(TaskReviewDTO taskReviewDTO) {
        Integer taskId = taskReviewDTO.getTask();
        if (!checkStatus(taskId, TaskStatusEnum.REVIEW)) {
            throw new CheckException("待审核的任务才需要审批");
        }
        TaskReviewEntity taskReviewEntity = new TaskReviewEntity();
        if (taskReviewDTO.isReview()) {
            taskMapper.updStatus(taskId, TaskStatusEnum.NOT_RECEIVED.getCode());
            //审批完成状态转到待接收状态
            taskReviewEntity.setStatus(TaskStatusEnum.REVIEW.getCode());
        } else {
            taskMapper.updStatus(taskId, TaskStatusEnum.REJECT.getCode());
            taskReviewEntity.setStatus(TaskStatusEnum.REJECT.getCode());
        }
        //记录审批记录
        taskReviewEntity.setTaskId(taskId);
        taskReviewEntity.setMessage(taskReviewDTO.getMsg());
        taskReviewEntity.setCreateTime(LocalDateTime.now().withNano(0));
        taskReviewMapper.insert(taskReviewEntity);

    }

    public boolean checkStatus(Integer taskId, TaskStatusEnum taskStatusEnum) {
        TaskGetQueryDTO taskEntity = taskMapper.selectById(taskId);
        if (taskEntity == null) {
            throw new CheckException("该任务不存在");
        }
        return taskStatusEnum.getCode().equals(taskEntity.getStatus());

    }

    public void receive(Integer taskId) {
        TaskGetQueryDTO taskEntity = taskMapper.selectById(taskId);
        if (taskEntity == null) {
            throw new CheckException("该任务不存在");
        }
        if (!TaskStatusEnum.isStatusBetween(taskEntity.getStatus(), 4, 11)) {
            throw new CheckException("未接收的任务才可以接收");
        }
        if (!com.sfj.system.utils.StringUtils.isIdInCommaString(taskEntity.getRfUsers(), String.valueOf(HeaderUtils.getUserId()))) {
            throw new CheckException("当前用户不可接收该任务");
        }
        if (com.sfj.system.utils.StringUtils.isIdInCommaString(taskEntity.getReceiveUsers(), String.valueOf(HeaderUtils.getUserId()))) {
            throw new CheckException("当前用户已经接收该任务");
        }
        String newReceiveUsers = StringUtils.addIdToCommaString(taskEntity.getReceiveUsers(), String.valueOf(HeaderUtils.getUserId()));
        taskEntity.setReceiveUsers(newReceiveUsers);
        String newReceiveUnits = StringUtils.addIdToCommaString(taskEntity.getReceiveUnits(), String.valueOf(HeaderUtils.getUserGroupIds()));
        taskEntity.setReceiveUnits(newReceiveUnits);

        //整改人员列表等于接收人员列表 说明已经全部接收
        if (StringUtils.isSameElements(taskEntity.getRfUsers(), taskEntity.getReceiveUsers())) {
            //当前状态已经超过要更新吃状态就不更新
            if (TaskStatusEnum.getByCode(taskEntity.getStatus()).getStep() <= TaskStatusEnum.PROCESSING.getStep()) {
                taskEntity.setStatus(TaskStatusEnum.PROCESSING.getCode());
            }
        } else {
            if (TaskStatusEnum.getByCode(taskEntity.getStatus()).getStep() <= TaskStatusEnum.RECEIVED.getStep()) {
                taskEntity.setStatus(TaskStatusEnum.RECEIVED.getCode());
            }

        }
        taskMapper.updReceiveAndStatus(taskEntity);
    }

    @Transactional
    public void process(ProblemProcessEntity problemProcessEntity) {
        problemProcessEntity.setRfUser(HeaderUtils.getUserId());
        problemProcessEntity.setRfUnit(HeaderUtils.getUserGroupIds());

        //存在即更新
        ProblemProcessEntity problemProcessById = problemProcessService.getProblemProcessById(problemProcessEntity.getProblemId(),
                problemProcessEntity.getTaskId(),
                problemProcessEntity.getRfUser());
        if (problemProcessById != null) {
            problemProcessById.setCheckMessage(problemProcessEntity.getCheckMessage());
            problemProcessById.setRfMeasures(problemProcessEntity.getRfMeasures());
            //if (TaskStatusEnum.REJECT.getCode().equals(problemProcessById.getStatus())) {
            problemProcessById.setStatus(TaskStatusEnum.PENDING_REVIEW.getCode());
            problemProcessById.setFile(problemProcessEntity.getFile());
            //清空驳回原因
            problemProcessById.setMessage(null);

            problemProcessService.updateProblemProcess(problemProcessById);

        } else {
            problemProcessService.createProblemProcess(problemProcessEntity);
            //更新整改问题状态
            problemService.updStatus(problemProcessEntity.getProblemId());
        }
    }

    //提交反馈任务
    public void processed(Integer taskId) {
        TaskGetQueryDTO taskEntity = taskMapper.selectById(taskId);
        if (taskEntity == null) {
            throw new CheckException("该任务不存在");
        }
        List<TaskProblemDescDTO> taskProblemDescDTOS = problemService.selectDesc(taskId, HeaderUtils.getUserId());
        if (taskProblemDescDTOS.stream()
                .anyMatch(dto -> ProblemStatusEnum.NOT_RECTIFIED.getCode().equals(dto.getStatus()) ||
                        ProblemStatusEnum.REJECT.getCode().equals(dto.getStatus()))
        ) {
            throw new CheckException("还有整改问题未处理");
        }
        if (!TaskStatusEnum.isStatusBetween(taskEntity.getStatus(), 4, 11)) {
            throw new CheckException("未反馈的任务才可以提交");
        }
        if (!com.sfj.system.utils.StringUtils.isIdInCommaString(taskEntity.getRfUsers(), String.valueOf(HeaderUtils.getUserId()))) {
            throw new CheckException("当前用户不可反馈该任务");
        }
        //更新整改时间
        problemProcessService.updateRectifyDate(taskId,HeaderUtils.getUserId());

        //存在驳回重新提交情况 去除逻辑

        //if (com.sfj.system.utils.StringUtils.isIdInCommaString(taskEntity.getFbUsers(), String.valueOf(HeaderUtils.getUserId()))) {
        //    throw new CheckException("当前用户已经反馈该任务");
        //}
        String newFbUsers = StringUtils.addIdToCommaString(taskEntity.getFbUsers(), String.valueOf(HeaderUtils.getUserId()));
        taskEntity.setFbUsers(newFbUsers);
        String newFbUnits = StringUtils.addIdToCommaString(taskEntity.getFbUnits(), String.valueOf(HeaderUtils.getUserGroupIds()));
        taskEntity.setFbUnits(newFbUnits);

        //整改人员列表等于反馈人员列表 说明已经全部反馈
        if (StringUtils.isSameElements(taskEntity.getRfUsers(), taskEntity.getFbUsers())) {
            //if (TaskStatusEnum.getByCode(taskEntity.getStatus()).getStep() <= TaskStatusEnum.PENDING_REVIEW.getStep()) {

                taskEntity.setStatus(TaskStatusEnum.PENDING_REVIEW.getCode());
            //}
        } else {
            if (TaskStatusEnum.getByCode(taskEntity.getStatus()).getStep() <= TaskStatusEnum.PENDING_REVIEWING.getStep()) {
                //部分待复核
                taskEntity.setStatus(TaskStatusEnum.PENDING_REVIEWING.getCode());
            } else if(TaskStatusEnum.getByCode(taskEntity.getStatus()).getStep() <= TaskStatusEnum.PENDING_REVIEWED.getStep()){
                //有新复核申请
                taskEntity.setStatus(TaskStatusEnum.NEW_REVIEW.getCode());
            }
        }
        if (taskEntity.getRjUsers() != null) {
            //去除当前驳回的用户
            removeUserIdFromRjUsers(taskEntity, String.valueOf(HeaderUtils.getUserId()));
        }
        taskMapper.updProcessAndStatus(taskEntity);
    }

    //删除其中一个
    private void removeUserIdFromRjUsers(TaskGetQueryDTO taskGetQueryDTO, String userIdToRemove) {
        String rjUsers = taskGetQueryDTO.getRjUsers();

        // 处理字符串前后的逗号（如 ",1,2," -> "1,2"）
        rjUsers = rjUsers.replaceAll("^,|,$", "");

        // 分割并处理
        List<String> userIds = Arrays.stream(rjUsers.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());

        // 移除目标ID（精确匹配）
        userIds.removeIf(userId -> userId.equals(userIdToRemove));

        // 重新组合
        String updatedRjUsers = userIds.isEmpty() ? null : String.join(",", userIds);

        // 更新实体
        taskGetQueryDTO.setRjUsers(updatedRjUsers);
    }
}
